<template>
  <div class="person-info">
    <ul class="menu">
      <li :class="['content', menuActive == index ? 'active-content' : '']" v-for="(item, index) in menuList" :key="index" @click="handleMenu(index)">
        {{ item }}
      </li>
    </ul>
    <div class="basic-info-box" v-show="menuActive == 0">
      <div class="basic-info">
        <MyHeader>
          <div slot="title">基本信息</div>
        </MyHeader>
        <div class="content">
          <el-row>
            <el-col :span="7">
              <el-form ref="uploadForm">
                <el-form-item prop="imgPath">
                  <uploadImg
                    @setCardPic="setCardPic"
                    ref="imgPath"
                    type="image"
                    :api="api"
                    :params="params"
                    :autoUpload="true"
                  />
                </el-form-item>
              </el-form>
            </el-col>
            <el-col :span="2">
              <div class="line"></div>
            </el-col>
            <el-col :span="15">
              <el-form
                :model="infoForm"
                label-width="100px"
                :rules="infoRules"
                ref="infoForm"
              >
                <el-form-item prop="name" label="姓名">
                  <el-input v-model="infoForm.name" />
                </el-form-item>
                <el-form-item prop="cellphone" label="手机号">
                  <span class="cell-phone">
                    {{ infoForm.cellphone.replace(/^(.{3})(?:\d+)(.{4})$/, "$1****$2") }}
                  </span>
                  <span @click="phoneDialog = true" class="edit-cellphone">
                    修改
                  </span>
                </el-form-item>
                <el-form-item prop="email" label="邮箱">
                  <el-input v-model="infoForm.email" />
                </el-form-item>
                <el-form-item prop="gender" label="性别">
                  <el-radio-group v-model="infoForm.gender">
                    <el-radio :label="1">男</el-radio>
                    <el-radio :label="0">女</el-radio>
                  </el-radio-group>
                </el-form-item>
                <el-form-item v-if="isArt" prop="nation" label="民族">
                  <el-input v-model="art_info.nation" />
                </el-form-item>
                <el-row v-if="isArt">
                  <el-col :span="18">
                    <el-form-item prop="newCellphone" label="联系方式">
                      <el-input v-model="art_info.cellphone" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label-width="0" prop="onlyMe" class="only-me">
                      <el-checkbox v-model="art_info.cellphone_hide"
                        >仅自己可见</el-checkbox
                      >
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item v-if="isArt" label="艺术家类型" prop="art_type">
                  <el-select filterable v-model="art_info.art_type">
                    <el-option
                      v-for="item in artTypeList"
                      :key="item.data_id"
                      :value="item.name"
                      :label="item.name"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item v-if="isArt" prop="position" label="职位">
                  <el-input
                    v-model="art_info.position"
                    placeholder="例如：中国美术家协会会员、学生、设计师"
                  />
                </el-form-item>
                <el-form-item v-if="isArt" prop="brief" label="简介">
                  <el-input
                    v-model="art_info.introduction"
                    type="textarea"
                    resize="none"
                    maxlength="2000"
                    show-word-limit
                  />
                </el-form-item>
              </el-form>
            </el-col>
          </el-row>
          <el-dialog
            :visible.sync="phoneDialog"
            width="600px"
            center
            :modal="false"
            :lock-scroll="true"
            title="修改手机号"
          >
            <el-form :model="editCellphone" :rules="editRules" ref="editCellphone">
              <el-form-item prop="cellphone">
                <el-input v-model="editCellphone.cellphone" placeholder="手机号"></el-input>
              </el-form-item>
              <el-form-item prop="ver_code" class="password">
                <el-input v-model="editCellphone.ver_code" @keyup.enter.native="submit" placeholder="验证码"></el-input>
                <span v-loading="loading" @click="inputCode" :class="['shortCode', wait ? 'timeCode' : '']">{{ codeMessage }}</span>
              </el-form-item>
            </el-form>
            <div class="dialog-footer">
              <el-button type="primary" @click="submit">确 定</el-button>
            </div>
          </el-dialog>
        </div>
      </div>
      <div v-if="isArt" class="big-deal">
        <MyHeader>
          <div slot="title">大事记</div>
        </MyHeader>
        <el-form
          :model="big_event"
          label-width="100px"
          ref="big_event"
          class="content"
        >
          <div v-for="(item, index) in big_event.dynamicItem" :key="index">
            <el-form-item label="时间" :prop="'dynamicItem.' + index + '.time'">
              <el-date-picker
                v-model="item.event_time"
                align="right"
                type="date"
                placeholder="选择日期"
                value-format="yyyy-MM-dd"
                :picker-options="pickerOptions"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="经历" :prop="'dynamicItem.' + index + '.event'">
              <el-input
                v-model="item.event"
                type="textarea"
                resize="none"
              ></el-input>
            </el-form-item>
          </div>
        </el-form>
        <div class="add-form" @click="addItem">
          <img src="../../../static/img/user/icon_plus.png" alt="">
          <span class="text">添加事记</span>
        </div>
      </div>
      <div class="save-btn all-center" @click="save">保存</div>
    </div>
    <div class="account-safe" v-show="menuActive == 1">
      <EditPassword />
    </div>
  </div>
</template>

<script>
import uploadImg from "@/components/uploadImg";
import MyHeader from "./common/myHeader";
import {getUserPhoto} from '@/utils/downloadFile'
import EditPassword from './editPassword.vue'
export default {
  name: "",
  components: {
    uploadImg,
    MyHeader,
    EditPassword
  },
  middleware: 'identityInfo',
  props: {},
  data() {
    const validateShort = (rule, value, callback) => {
      const reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/ // 手机号正则
      if (!value) {
        return callback(new Error('手机号不能为空'))
      }
      if (!reg_tel.test(value)) {
        callback(new Error('您输入的手机号格式不正确'))
      } else {
        callback()
      }
    }
    return {
      menuList: [
        '基本信息',
        '账号安全'
      ],
      menuActive: 0,
      artEventData: [],
      art_info: {
        cellphone: '',
        cellphone_hide: false,
        introduction: '',
        position: '',
        art_type: '',
        nation: ''
      },
      loading: false,
      phoneDialog: false,
      userInfo: {},
      api: "",
      params: {},
      imgPath: '',
      isArt: false,
      codeMessage: '获取短信验证码',
      wait: false,
      timer: null,
      editCellphone: {
        cellphone: '',
        ver_code: ''
      },
      editRules: {
        cellphone: [
          { required: true, trigger: 'blur', validator: validateShort },
        ],
        ver_code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { max: 6, min: 6, message: '验证码长度为6', trigger: 'blur' }
        ]
      },
      infoForm: {
        name: "",
        gender: 1,
        cellphone: "",
        email: ""
      },
      artTypeList: [],
      big_event: {
        dynamicItem: [{
          event_time: '',
          event: ''
        }],
      },
      infoRules: {
        name: [
          {
            required: true,
            message: "请输入姓名",
            trigger: "change",
          },
        ],
        gender: [
          {
            required: true,
            message: "请选择性别",
            trigger: "change",
          },
        ],
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
    };
  },
  computed: {},
  watch: {},
  created () {},
  mounted () {
    this.getProductType()
    // this.artEvent()
    /*详情的时候设定显示图片的路径 setEditImg是uploadImg组件提供的方法 imgpath是子组件的ref属性（看使用的组件）*/
    // this.$refs.imgPath.setEditImg("");
    // 在父组件操控参数和接口
    this.params = {
      op: "upload_file",
      name: "photo",
      userid: this.$store.state.user?.info?.user_info?.data_id
    };
    this.api = "uplpadHeadPhoto";
    // console.log('this.$store.state.user.info', this.$cookies.get('userInfo'))
    // if (this.$store.state.user.info.user_info.art_info.data_id) {
      this.getUserInfo();
    // }
  },
  methods: {
    // 大事记
    // artEvent() {
    //   this.$api.artEvent({ art_id: this.$store.state.user?.info?.user_info?.art_info.data_id }).then(res => {
    //     this.big_event.dynamicItem = Array.isArray(res.result.item_list) ? res.result.item_list : [{
    //       event_time: '',
    //       event: ''
    //     }]
    //   })
    // },
    handleMenu(index) {
      this.menuActive = index
      // if (index == 1) {
      //   this.refresh()
      // } else if (index == 2) {
      //   this.$refs.adminFamousWorks.refresh()
      // }
    },
    getProductType() {
      this.$api.getProductType({ art_type: 1 }).then(res => {
        this.artTypeList = res.result.item_list.filter((item) => {
          return item.parent_id === -1;
        });
      })
    },
    // 根据id查询指定艺术家
    artDesc(data_id) {
      const params = {
        data_id: data_id
      }
      this.$api.artDesc(params).then(res => {
        console.log('art_info', res.result)
        this.art_info.cellphone = res.result.cellphone
        this.art_info.cellphone_hide = res.result.cellphone_hide == 1
        this.art_info.position = res.result.position
        this.art_info.nation = res.result.nation
        // this.infoForm.nation = res.result.nation
        // this.infoForm.art_type = res.result.nation
        this.art_info.art_type = res.result.art_type
        this.art_info.introduction = res.result.introduction
        this.big_event.dynamicItem = Array.isArray(res.result.big_event) ? res.result.big_event : [{
          event_time: '',
          event: ''
        }]
        console.log(this.big_event.dynamicItem)
      })
    },
    // 获取短信验证码
    inputCode() {
      this.$refs['editCellphone'].validateField('cellphone', valid => {
        if (!valid) {
          this.loading = true
          this.getVercode()
        }
      })
    },
    // 获取短信验证码
    getVercode() {
      const params = {
        data_id: this.params.userid,
        op: "send_change_cellphone_ver_code",
        reciever: this.editCellphone.cellphone
      }
      this.$api.getVercode({ ...params }).then(res => {
        if (res.status == '$SUCCESS') {
          this.loading = false
          this.$message.success('获取短信验证码')
          let time = 60
          this.wait = true
          this.timer = this.codeMessage = time + 's后重新发送'
          setInterval(() => {
            time--
            this.codeMessage = time + 's后重新发送'
            if (time <= 0) {
              this.codeMessage = '获取验证码'
              clearInterval(this.timer)
            }
          }, 1000);
        }
      })
    },
    // 关闭弹窗
    close() {
      this.phoneDialog = false
      this.$refs.editCellphone.resetFields()
    },
    submit() {
      this.$refs.editCellphone.validate((valid) => {
        if (valid) {
          const params = {
            ...this.editCellphone
          }
          this.$api.changePhone({ ...params }, { op: "change_cellphone", data_id: this.params.userid }).then(res => {
            if (res.status == '$SUCCESS') {
              this.$message.success('手机号码修改成功')
              this.getUserInfo()
              this.close()
            } else {
              this.$message.error(res.message)
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 获取用户信息
    getUserInfo() {
      console.log('用户信息：', this.$store.state.user.info)
      const params = {
        data_id: this.$store.state.user?.info?.user_info?.data_id,
      };
      this.$api.getUserInfo(params).then((res) => {
        if (res.status == "$SUCCESS") {
          // this.$store.commit('user/SET_INFO', res.result)
          console.log('res.result', res.result)
          this.isArt = res.result.user_type - 0 === 2 || res.result.user_type - 0 === 0
          this.userInfo = res.result
          console.log('艺术家id', res.result?.art_info?.data_id)
          if (res.result?.art_info?.data_id) {
            this.artDesc(res.result.art_info.data_id)
          }
          this.infoForm = {
            name: res.result.name,
            email: res.result.email,
            gender: res.result.gender,
            cellphone: res.result.cellphone,
            // nation: res.result.nation,
            // art_type: res.result.art_info.type
          }
          this.editCellphone.cellphone = this.infoForm.cellphone
          if (this.userInfo.photo != 'default.png') {
            console.log('头像', this.userInfo.photo)
            this.$refs.imgPath.setEditImg(this.userInfo.photo)
          }
        }
      });
    },
    /*执行uploadImg组件报出来的事件，path就是显示图片的路径*/
    async setCardPic(path, pic) {
      // this.form[pic] = path
      console.log('+++++', path, pic);
      await this.$api.updateUserDesc({ photo: path }, { data_id: this.$store.state.user?.info?.user_info?.data_id })
    },
    addItem() {
      this.big_event.dynamicItem.push({
        event_time: "",
        event: "",
      });
      console.log(this.big_event.dynamicItem)
    },
    save() {
      this.$refs.infoForm.validate(async (valid) => {
        if (valid) {
          const params = {
            ...this.infoForm
          }
          console.log(params)
          // const res = await this.$api.changePhone({ ...params }, { data_id: this.$store.state.user?.info?.user_info?.data_id })
          //   if (res.status == '$SUCCESS') {
          //     this.$message.success('用户信息修改成功')
          //     this.getUserInfo()
          //   } else {
          //     this.$message.error(res.message)
          //   }
          console.log({ ...this.art_info, ...params })
          const data = {
            ...this.art_info,
            big_event: this.big_event.dynamicItem,
            cellphone_hide: this.art_info.cellphone_hide ? 1 : 0
          }
          if (this.big_event.dynamicItem.length === 0) {
            await this.$api.createEvent(this.big_event.dynamicItem.map(item => {
              item.art_id = this.$store.state.user?.info?.user_info?.art_info?.data_id
              return item;
            }))
          } else {
            await this.$api.updateEvent(this.big_event.dynamicItem, { data_id: this.$store.state.user?.info?.user_info?.art_info?.data_id })
          }
          const res2 = await this.$api.updateUserDesc(params, { data_id: this.$store.state.user?.info?.user_info?.data_id })
          const res3 = await this.$api.updateArtDesc(data, { data_id: this.$store.state.user?.info?.user_info?.art_info?.data_id })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
  },
};
</script>

<style scoped lang="less">
.person-info {
  padding: 60px 276px 80px;

  .menu {
    height: 100%;
    margin-right: 90px;
    margin-bottom: 50px;
    margin: 0 90px 50px 100px;

    .content {
      // width: 150px;
      line-height: 24px;
      margin-right: 80px;
      display: inline-block;
      font-size: 24px;
      color: #999;
      cursor: pointer;
      list-style-type: none;

      &.active-content {
        color: #000;
      }

      &:last-child {
        margin-bottom: 0;
      }
    }
  }

  .basic-info,
  .big-deal {
    background: #fff;
  }

  ::v-deep(.el-dialog__footer) {
    padding: 10px 100px 20px;
  }

  ::v-deep(.el-textarea .el-input__count) {
    background-color: #f3f4f4;
  }

  ::v-deep(.el-button--primary) {
    width: 100%;
    height: 60px;
    background-color: #DFCBB6;
    border: 0;
    border-radius: 0;
    margin-bottom: 30px;
    font-size: 24px;
  }

  .save-btn {
    width: 220px;
    height: 48px;
    display: flex;
    background: #e0cbb4;
    text-align: center;
    margin: 0 auto;
    margin-top: 40px;
    font-size: 16px;
    color: #333333;
  }

  .content {
    padding: 40px 96px 0 48px;

    .line {
      width: 1px;
      height: 449px;
      background: #f3f4f4;
    }

    .only-me {
      text-align: right;
    }

    .cell-phone {
      font-size: 16px;
      color: #333333;
    }

    .edit-cellphone {
      font-size: 16px;
      color: #C5A37D;
      cursor: pointer;
    }

    .shortCode {
      position: absolute;
      right: 0;
      cursor: pointer;
      color: #DFCBB6;
      background-color: #fff;

      &.timeCode {
        color: #999;
        pointer-events: none;
      }
    }
  }

  .add-form {
    padding: 0 0 45px 110px;

    .text {
      font-size: 16px;
      font-weight: 400;
      color: #333333;
    }

    img {
      margin-right: 33px;
    }
  }

  ::v-deep(.el-input__inner) {
    background-color: #f3f4f4;
    border-radius: 0;
  }

  ::v-deep(input::-webkit-input-placeholder) {
    color: #999;
  }

  ::v-deep(.el-radio__inner:hover) {
    border-color: #ccc;
  }

  ::v-deep(.el-radio__input.is-checked .el-radio__inner) {
    background: #fff;
    border-color: #ccc;
  }

  ::v-deep(.el-radio__inner::after) {
    background: #333;
  }

  ::v-deep(.el-radio__input.is-checked + .el-radio__label) {
    color: #333;
  }

  ::v-deep(.el-textarea__inner) {
    background: #f3f4f4;
    border-radius: 0;
  }

  .basic-info {
    margin-bottom: 40px;
  }

  .big-deal {
    ::v-deep(.el-date-editor.el-input) {
      width: 100%;
    }

    .content {
      padding-bottom: 45px;
    }
  }
}
</style>
